/*
* @(#)WeixinServlet.java 1.0 Sep 6, 2013
*
* Copyright @2011-2011 Gopay Information and Technology Co., Ltd.
* Sanyunqiao, Chaoyang, Beijing, 100027, China.
* All Rights Reserved.
*
* This software is the confidential and proprietary information of
* Gopay Information and technology Co., Ltd. ("Confidential Information").
* You shall not disclose such Confidential Information and shall use it only in
* accordance with the terms of the license agreement you entered into with Gopay.
*/
package com.neo.debade.web.servlet;

import java.io.IOException;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.neo.debade.weixin.service.IWeixinService;
import com.neo.debade.weixin.util.WeixinUtil;

/**
 *
 * @author zhong_xin
 * @version 1.0 Sep 6, 2013
 */
public class WeixinServlet extends BaseServlet {

	/**
	 * 
	 * @by zhong_xin - Sep 6, 2013 12:26:25 PM
	 */
	private static final long serialVersionUID = 1L;
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		
		// 认证
		wxAuth(req, resp);
	}
	
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		// 通讯消息
		wxProcess(req, resp);
	}
	
	
	/**
	 * 公众号接口认证.
	 * @param request
	 * @param response
	 * @by zhong_xin - Sep 6, 2013 1:59:49 PM
	 */
	public void wxAuth(HttpServletRequest request, HttpServletResponse response) {
		
		logger.info("*********** enter wx auth ****************");
		
		String token = "1234";
		String ret = WeixinUtil.auth(request, response, token);
		if (ret != null) {
			logger.info("*********** auth succ ****************");
			print(response, ret);
		}
	}
	
	
	/**
	 * 通讯消息处理.
	 * @param request
	 * @param response
	 * @by zhong_xin - Sep 6, 2013 2:33:11 PM
	 */
	public void wxProcess(HttpServletRequest request, HttpServletResponse response) {
		
		logger.info("*********** enter wx process ****************");
		
		IWeixinService weixinService = (IWeixinService) getWebApplicationContext().getBean("weixinService");
		
		Map<String, String> map = WeixinUtil.readRequest(request);
		
		String retMsg = weixinService.processMessage(map);
		
		if (retMsg != null && retMsg.length() > 0) {
			logger.info("resp message: " + retMsg);
			print(response, retMsg);
		}
		
	}

}
